import { Banner, ProductCategories, ProductDetails } from "src/services/products-service";

export const productStore = {
	state: {
		recommendProducts: [],
		categories: [],
		categorieProducts: [],
		pointProducts: [],
		selectedCategory: 0,
		banners: [],
		recommendServices: [],
		productDetails: {},
		typeRecommend: [],
		shoppingCarList: [],
		isShowShoppingCar: false,
		orderProducts: [],
		address: '假地址',
	},
	mutations: {
		setRecommendProducts(state, payload: ProductDetails[]) {
			state.recommendProducts = payload;
		},
		setRecommendServices(state, payload: ProductDetails[]) {
			state.recommendServices = payload;
		},
		setCategories(state, payload: ProductCategories[]) {
			state.categories = payload;
		},
		setCategorieProducts(state, payload: ProductDetails[]) {
			state.categorieProducts = payload;
		},
		setSelectedCategory(state, payload: string | number) {
			state.selectedCategory = payload;
		},
		setSalesBanners(state, payload: Banner[]) {
			state.banners = payload;
		},
		setProductDetails(state, payload: ProductDetails) {
			state.productDetails = payload
		},
		setPointProducts(state, payload: ProductDetails[]) {
			state.pointProducts = payload
		},
		setTypeRecommend(state, payload: ProductDetails[]) {
			state.typeRecommend = payload
		},
		addToShoppingCar(state, payload: number) {
			const { id, specs } = state.productDetails
			const item = {
				count: payload,
				id: 0,
				price: {
					money: 0,
					points: 0
				},
				specId: 0,
				product: state.productDetails
			}
			if (specs && specs[0]) {
				item.id = id;
				item.price = specs[0].price;
				item.specId = specs[0].id;
			}
			let existItem = state.shoppingCarList.find(i => {
				return i.id === item.id && i.specId === item.specId;
			}
			)
			if (existItem) {
				existItem.count += item.count;
			} else {
				existItem = item;
			}
			const tempList = state.shoppingCarList
				.filter(i => !(i.id === item.id && i.specId === item.specId));
			tempList.push(existItem);
			state.shoppingCarList = tempList;
		},
		removeFromShoppingCar(state, ids = []) {
			state.shoppingCarList = state.shoppingCarList
				.filter(({ id: i }) => ids.every(id => i !== id));
		},
		setCountFromShoppingCar(state, { id, count }) {
			state.shoppingCarList.forEach((item) => {
				if (item.id === id) {
					item.count = count
				}
			});
		},
		closeShoppingCar(state) {
			state.isShowShoppingCar = false
		},
		openShoppingCar(state) {
			state.isShowShoppingCar = true
		},
		goToProductOrder(state, orderProducts) {
			state.orderProducts = orderProducts
		},
		setAddress(state, address) {
			state.address = address
		},
		clearSalesOrder(state) {
			state.orderProducts = []
		}
	}
};
